<!-- 脚本 -->
<script setup>
// 导入
import { ref, onMounted, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
import { User, Lock, Iphone, Key } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useTokenStore } from '@/stores/token.js'
import { userLoginService, userRegisterService, userTypeService } from "@/api/user.js";
import { setCookie, getCookie, deleteCookie } from '@/utils/cookie.js';

const router = useRouter()
const tokenStore = useTokenStore()
const form = ref(null)
// 控制"记住我"复选框的状态
const rememberMe = ref(false)

// 控制注册与登录表单的显示， 默认显示登录
const isRegister = ref(false);
// 定义数据模型
const userDataModel = ref({
  username: "",
  password: "",
  rePassword: "",
  phone: "",
  code: "",
  keyword: ""
});

import { generateCaptcha } from '@/utils/captcha'
// 验证码相关
const captchaImgUrl = ref('')
const captchaText = ref('')
const inputCaptcha = ref('')
const verifyResult = ref('')

// 刷新验证码
const refreshCaptcha = () => {
  // 生成验证码图片的 base64 数据
  const canvas = document.createElement('canvas')
  canvas.width = 130
  canvas.height = 38
  captchaText.value = generateCaptcha(canvas)
  captchaImgUrl.value = canvas.toDataURL('image/png')
}

// 验证验证码
const verifyCaptcha = () => {
  if (!inputCaptcha.value) {
    verifyResult.value = '请输入验证码'
    return
  }

  if (inputCaptcha.value.toLowerCase() === captchaText.value.toLowerCase()) {
    verifyResult.value = '验证成功'
  } else {
    verifyResult.value = '验证码错误'
    // 延迟1秒后刷新验证码
    setTimeout(() => {
      refreshCaptcha()
    }, 1000)
  }
}

//校验密码的函数
const checkRePassword = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请再次确认密码"));
  } else if (value !== userDataModel.value.password) {
    callback(new Error("请确保两次输入的密码一样"));
  } else {
    callback();
  }
};

//定义表单校验规则
const rules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 5, max: 16, message: "长度为5~16位非空字符", trigger: "blur" },
  ],
  keyword: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 5, max: 16, message: "长度为5~16位非空字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 16, message: "长度为6~16位非空字符", trigger: "blur" },
  ],
  rePassword: [{ validator: checkRePassword, trigger: "blur" }],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" }
  ],
  code: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { min: 4, max: 4, message: "验证码长度为4位", trigger: "blur" },
  ],
};

// 注册
const register = async () => {
  // 表单校验
  form.value.validate(async (valid) => {
    if (valid) {
      // 表单校验通过，发送注册请求
      let result = await userRegisterService(userDataModel.value);
      if (result.code === 200) {
        // 注册成功
        ElMessage.success(result.message);
        // 清空表单
        clearUserData();
        // 切换到登录界面
        isRegister.value = false;
      } else {
        // 注册失败
        ElMessage.error(result.message);
      }
    } else {
      // 表单校验失败
      ElMessage.error("请填写完整并检查输入");
    }
  });
};

// 登录
const login = async () => {
  // 清空上一次的验证码输入和结果
  inputCaptcha.value = userDataModel.value.code
  verifyResult.value = ''

  // 先进行验证码校验
  verifyCaptcha()

  if (verifyResult.value === '验证成功') {
    // 验证码通过，再进行表单校验
    form.value.validate(async (valid) => {
      if (valid) {
        // 表单校验通过，发送登录请求
        let result = await userLoginService(userDataModel.value);
        if (result.code === 200) {
          // 保存token到store中
          tokenStore.setToken(result.data.token);
          
          // 处理"记住我"功能
          if (rememberMe.value) {
            // 如果勾选了"记住我"，将用户信息保存到cookie中，有效期7天
            setCookie('username', userDataModel.value.keyword, 7);
            setCookie('password', userDataModel.value.password, 7);
          } else {
            // 如果没有勾选"记住我"，删除cookie中的用户信息
            deleteCookie('username');
            deleteCookie('password');
          }
          
          if(tokenStore.token){
          // 根据用户类型跳转到不同的页面
          let userType = await userTypeService();
          
          let type = userType.data.assignment.menuIds
          console.log(userType.data.assignment.menuIds)
          
          if (type) {
            console.log(type)
            console.log("管理员");
            // 管理员跳转到管理页面
            ElMessage.success("欢迎回来，尊贵的管理员！")
            router.push('/admin')
          } else {
            console.log("普通用户");
            console.log(type)
            // 普通用户跳转到首页
            ElMessage.success(result.message);
            router.push('/home')
          }
        }
        } else {
          ElMessage.error(result.message);
          // 登录失败，刷新验证码
          refreshCaptcha()
        }
      } else {
        // 表单校验失败
        ElMessage.error("请填写完整并检查输入");
      }
    });
  } else if (verifyResult.value !== '请输入验证码') {
    // 验证码校验失败（不是因为空输入）
    ElMessage.error(verifyResult.value)
  }
};

//清空数据模型的数据
const clearUserData = () => {
  userDataModel.value = {
    username: "",
    password: "",
    rePassword: "",
    phone: "",
    code: "",
  };
};

// 监听键盘事件
const handleKeyPress = (event) => {
  if (event.key === 'Enter') {
    if (isRegister.value) {
      register();
    } else {
      login();
    }
  }
};

// 组件挂载时添加事件监听
onMounted(() => {
  // 刷新验证码
  refreshCaptcha();
  // 添加键盘事件监听
  window.addEventListener('keypress', handleKeyPress);
  
  // 从cookie中获取保存的用户信息
  const savedUsername = getCookie('username');
  const savedPassword = getCookie('password');
  // 如果存在保存的用户信息，则自动填充表单
  if (savedUsername && savedPassword) {
    userDataModel.value.keyword = savedUsername;
    userDataModel.value.password = savedPassword;
    // 自动勾选"记住我"复选框
    rememberMe.value = true;
  }
});

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('keypress', handleKeyPress);
});
</script>

<!-- 模板 -->
<template>
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <!-- 注册表单 -->
      <el-form ref="form" size="large" autocomplete="off" v-if="isRegister" :model="userDataModel" :rules="rules">
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="userDataModel.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="userDataModel.password"></el-input>
        </el-form-item>
        <el-form-item prop="rePassword">
          <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次密码"
            v-model="userDataModel.rePassword"></el-input>
        </el-form-item>
        <el-form-item prop="phone">
          <el-input :prefix-icon="Iphone" placeholder="请输入手机号" v-model="userDataModel.phone"></el-input>
        </el-form-item>
        <!-- 注册按钮 -->
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="register">
            注册
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="
            isRegister = false;
          clearUserData();
          ">
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>
      <!-- 登录表单 -->
      <el-form ref="form" size="large" autocomplete="off" v-else :model="userDataModel" :rules="rules">
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="keyword">
          <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="userDataModel.keyword"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码"
            v-model="userDataModel.password"></el-input>
        </el-form-item>
        <el-form-item prop="code">
          <div style="display: flex; align-items: center; width: 100%;">
            <div style="width: 50%;">
              <el-input type="text" :prefix-icon="Key" placeholder="请输入验证码" v-model="userDataModel.code"
                style="width: 100%;"></el-input>
            </div>
            <div style="width: 50%; display: flex; justify-content: flex-end; align-items: center;">
              <img :src="captchaImgUrl" @click="refreshCaptcha" alt="验证码"
                style="height: 38px; cursor: pointer; border-radius: 4px; border: 1px solid #eee; margin-right: 8px;" />
              <span @click="refreshCaptcha"
                style="color: #409EFF; cursor: pointer; user-select: none; margin-left: 0; font-size: 14px;">看不清？换一张</span>
            </div>
          </div>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox v-model="rememberMe">记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>
        <!-- 登录按钮 -->
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="login">登录</el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="
            isRegister = true;
          clearUserData();
          ">
            注册 →
          </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<!-- 样式 -->
<style lang="scss" scoped>
/* 样式 */
.login-page {
  height: 100vh;
  background-color: #fff;

  .bg {
    background: url("@/assets/images/logo.png") no-repeat 80% center / 400px auto,
      url("@/assets/images/login_bg.jpg") no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }

  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;

    .title {
      margin: 0 auto;
    }

    .button {
      width: 100%;
    }

    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
